<template>
	<a-upload name="avatar" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
		action="http://localhost:3000/api/vueUpload" :before-upload="beforeUpload" @change="handleChange">
		<img v-if="imageUrl" :src="imageUrl" alt="avatar" style="max-width:100px" />
		<div v-else>
			<!-- todo -->
			<loading-outlined v-if="loading" />
			<plus-outlined v-else />
			<div class="ant-upload-text">Upload</div>
		</div>
	</a-upload>
</template>

<script lang="ts">
	import { defineComponent } from "vue";
	import { PlusOutlined, LoadingOutlined } from "@ant-design/icons-vue";
	import { message } from 'ant-design-vue';
	//表示把image对象转换成base64编码
	function getBase64(img : any, callback : any) {
		const reader = new FileReader();
		reader.addEventListener('load', () => callback(reader.result));
		reader.readAsDataURL(img);
	}

	export default defineComponent({
		components: {
			PlusOutlined,
			LoadingOutlined,
		},
		data() {
			return {
				loading: false,
				imageUrl: "",
			};
		},
		methods: {
			//表示文件上传的时候触发的方法
			handleChange(info : any) {
				if (info.file.status === "uploading") {
					this.loading = true;
					return;
				}
				if (info.file.status === "done") {
					console.log(info.file.response.url);


					// Get this url from response in real world.
					getBase64(info.file.originFileObj, (imageUrl : any) => {
						this.imageUrl = imageUrl;
						this.loading = false;
					});
				}
				if (info.file.status === "error") {
					this.loading = false;
				}
			},
			//上传之前触发的方法
			beforeUpload(file : any) {
				const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
				if (!isJpgOrPng) {
					message.error("文件类型必须是jpg以及png!");
				}
				const isLt2M = file.size / 1024 / 1024 < 2;
				if (!isLt2M) {
					message.error("图片大小必须小于 2MB!");
				}
				return isJpgOrPng && isLt2M;
			},
		},
	});
</script>

<style lang="scss">
	.avatar-uploader>.ant-upload {
		width: 128px;
		height: 128px;
	}

	.ant-upload-select-picture-card i {
		font-size: 32px;
		color: #999;
	}

	.ant-upload-select-picture-card .ant-upload-text {
		margin-top: 8px;
		color: #666;
	}
</style>